package com.api.controller;

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import com.api.entity.RequestHeader;
import com.api.entity.RequestParams;
import com.api.entity.ResponseParams;

public class BaseController {
	/**
	 * 获取页面上 全部参数 封装成List<Requestparams>
	 * 
	 * @return
	 */
	public List<RequestParams> getManagerApi_requestParams(HttpServletRequest req) {
		String requestNames = req.getParameter("requestParams_index_values");
		if (StringUtils.isEmpty(requestNames)) {
			return null;
		}
		String[] requestNamesList = requestNames.split("_");
		List<RequestParams> list = new ArrayList<RequestParams>();

		for (int i = 0; i < requestNamesList.length; i++) {
			RequestParams data = new RequestParams();
			String name = req.getParameter("requestParams_" + requestNamesList[i] + "_name");
			data.setName(name);

			String val = req.getParameter("requestParams_" + requestNamesList[i] + "_val");
			data.setVal(val);
			String must = req.getParameter("requestParams_" + requestNamesList[i] + "_must");
			data.setIs_must(must);
			String notes = req.getParameter("requestParams_" + requestNamesList[i] + "_notes");
			data.setNotes(notes);
			list.add(data);
		}
		return list;
	}

	/**
	 * 获取页面上 全部参数 封装成List<Requestparams>
	 * 
	 * @return
	 */
	public List<RequestHeader> getManagerApi_requestHeader(HttpServletRequest req) {
		String requestNames = req.getParameter("requestHeader_index_values");
		if (StringUtils.isEmpty(requestNames)) {
			return null;
		}
		String[] requestNamesList = requestNames.split("_");
		List<RequestHeader> list = new ArrayList<RequestHeader>();

		for (int i = 0; i < requestNamesList.length; i++) {
			RequestHeader data = new RequestHeader();
			String name = req.getParameter("requestHeader_" + requestNamesList[i] + "_name");
			data.setName(name);

			String val = req.getParameter("requestHeader_" + requestNamesList[i] + "_val");
			data.setVal(val);

			String notes = req.getParameter("requestHeader_" + requestNamesList[i] + "_notes");
			data.setNotes(notes);
			list.add(data);
		}
		return list;
	}

	// public int boolRequestParams(){
	// List<Requestparams> list = getManagerApi_requestParams();
	// if(list==null||list.size()==0){
	// return 1;
	// }
	// for (int i = 0; i < list.size(); i++) {
	// if(StrKit.isBlank(list.get(i).getName())){
	// return 2;
	// }
	// if(Boolean.valueOf(list.get(i).getIsMust().toString()) && StrKit.isBlank(list.get(i).getVal())){
	// return 3;
	// }
	// }
	// return 1;
	// }

	public List<ResponseParams> getManagerApi_responseParams(HttpServletRequest req) {
		String responseNames = req.getParameter("responseParams_index_values");
		if (StringUtils.isEmpty(responseNames)) {
			return null;
		}
		String[] responseNamesList = responseNames.split("_");
		List<ResponseParams> list = new ArrayList<ResponseParams>();

		for (int i = 0; i < responseNamesList.length; i++) {
			ResponseParams data = new ResponseParams();
			String name = req.getParameter("response_" + responseNamesList[i] + "_name");
			data.setName(name);
			String val = req.getParameter("response_" + responseNamesList[i] + "_val");
			data.setVal(val);
			String notes = req.getParameter("response_" + responseNamesList[i] + "_notes");
			data.setNotes(notes);
			list.add(data);
		}
		return list;
	}

	/**
	 * 添加Model消息
	 * 
	 * @param message
	 */
	protected void addMessage(Model model, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages) {
			sb.append(message).append(messages.length > 1 ? "<br/>" : "");
		}
		model.addAttribute("message", sb.toString());
	}

	/**
	 * 客户端返回JSON字符串
	 * 
	 * @param response
	 * @param object
	 * @return
	 */
//	protected String renderString(HttpServletResponse response, Object object) {
//		return renderString(response, JsonMapper.toJsonString(object), "application/json");
//	}

	/**
	 * 客户端返回字符串
	 * 
	 * @param response
	 * @param string
	 * @return
	 */
	protected String renderString(HttpServletResponse response, String string, String type) {
		try {
			response.reset();
			response.setContentType(type);
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * 参数绑定异常
	 */
	@ExceptionHandler({ BindException.class, ConstraintViolationException.class, ValidationException.class })
	public String bindException() {
		return "error/400";
	}

	/**
	 * 初始化数据绑定 1. 将所有传递进来的String进行HTML编码，防止XSS攻击 2. 将字段中Date类型转换为String类型
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}

			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				try {
					setValue(DateUtils.parseDate(text));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			// @Override
			// public String getAsText() {
			// Object value = getValue();
			// return value != null ? DateUtils.formatDateTime((Date)value) : "";
			// }
		});
	}

}
